package util

import (
    "fmt"
    "github.com/go-playground/locales/zh_Hans_CN"
    trans "github.com/go-playground/universal-translator"
    "github.com/go-playground/validator/v10"
    trans_zh "github.com/go-playground/validator/v10/translations/zh"
    "reflect"
)

// 自定义校验方法
func Validator(data interface{}) (bool, string) {
    validate := validator.New()
    zh_Hans := trans.New(zh_Hans_CN.New())
    locale, _ := zh_Hans.GetTranslator("zh_Hans_CN")
    err := trans_zh.RegisterDefaultTranslations(validate, locale)
    if err != nil {
        fmt.Println("err: ", err)
    }

    // 结构体字段映射到label
    validate.RegisterTagNameFunc(func(field reflect.StructField) string {
        label := field.Tag.Get("label")
        return label
    })

    err = validate.Struct(data)
    if err != nil {
        for _, v := range err.(validator.ValidationErrors) {
            return false, v.Translate(locale)
        }
    }
    return true, ""
}
